package cn.car91.activity;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import cn.car91.R;
import cn.car91.activity.MapActivity.MapType;
import cn.car91.adapter.RepairShopListAdapter;
import cn.car91.bean.AreaParam;
import cn.car91.bean.District;
import cn.car91.bean.RepairShop;
import cn.car91.bean.Street;
import cn.car91.http.HttpHandler;
import cn.car91.pager.RepairShopPager;
import cn.car91.utils.Car91JsonUtil;
import cn.car91.utils.DensityUtils;
import cn.car91.utils.EarthUtil;
import cn.car91.utils.EarthUtil.Location;
import cn.car91.utils.MobileUtils;
import cn.car91.utils.RegexUtil;
import cn.car91.view.HeaderView;
import cn.car91.view.HerilyAlertDialog;
import cn.car91.view.HerilyAlertDialog.Builder;
import cn.car91.view.MyListView;
import cn.car91.view.PullToRefreshView;
import cn.car91.view.PullToRefreshView.OnFooterRefreshListener;
import cn.car91.view.PullToRefreshView.OnHeaderRefreshListener;

import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.util.LogUtils;
import com.lidroid.xutils.view.annotation.ViewInject;

public class RepairShopMainActivity extends BaseListFragment {

    private RepairShopPager repairShopPager = new RepairShopPager();
    // 列表页面参数
    // @ViewInject(R.id.repairshop_list)
    MyListView repairShopList;
    @ViewInject(R.id.none)
    View none;
    @ViewInject(R.id.repairshop_pull_refresh)
    PullToRefreshView pullToRefreshView;
    @ViewInject(R.id.repairshop_list_select_rgrade)
    Spinner rgradeSpinner;

    RepairShopListAdapter repairShopListAdapter = null;
    // 初始化一个自定义的Dialog
    // Dialog dialog = null;

    PopupWindow popupWindow = null;
    List<District> districts;
    List<Street> streets;
    LinearLayout placeList;
    RadioGroup radioGroupFirst;
    RadioGroup radioGroupSecond;

    @ViewInject(R.id.repairshop_list_order)
    LinearLayout orderView;

    private String orderby = OrderBy.Default;
    private boolean addDate = false;

    private AreaParam areaParam = new AreaParam();
    private Float distance = null;
    private Integer rgrade = null;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        return inflater.inflate(R.layout.activity_repairshop_main, container,
                false);
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        repairShopList = (MyListView) getListView();
        placeList = (LinearLayout) ((LayoutInflater) getActivity()
                .getSystemService(Activity.LAYOUT_INFLATER_SERVICE)).inflate(
                R.layout.view_area_list_second, null);
        placeList.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
                LayoutParams.MATCH_PARENT));
        placeList.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                closePopupWindow();
            }
        });
        repairShopListAdapter = new RepairShopListAdapter(getActivity(),
                R.layout.view_repairshop_item);
        // repairShopList.setAdapter(repairShopListAdapter);
        setListAdapter(repairShopListAdapter);
        radioGroupFirst = (RadioGroup) placeList.findViewById(R.id.area_first);
        radioGroupSecond = (RadioGroup) placeList
                .findViewById(R.id.area_second);

        int cid = getCar91Application().getPlacePreferences()
                .getInt("city", -1);
        areaParam.paramName = "cid";
        areaParam.paramValue = String.valueOf(cid);
        initSort();

        // repairShopList.setPullLoadEnable(false);
        // repairShopList.setPullRefreshEnable(false);
        // repairShopList.setXListViewListener(onRepairShopViewListener);

        pullToRefreshView
                .setOnHeaderRefreshListener(new OnHeaderRefreshListener() {

                    @Override
                    public void onHeaderRefresh(PullToRefreshView view) {
                        // Toast.makeText(getActivity(), "刷新数据!", 0).show();
                        addDate = false;
                        repairShopPager.reset();
                        /*
                         * repairShopList.getmFooterView().setState(
                         * XListViewFooter.STATE_NORMAL);
                         */
                        getData();
                    }
                });

        pullToRefreshView
                .setOnFooterRefreshListener(new OnFooterRefreshListener() {

                    @Override
                    public void onFooterRefresh(PullToRefreshView view) {
                        // Toast.makeText(getActivity(), "加载更多数据!", 0).show();
                        addDate = true;
                        getData();
                    }
                });

        getActivity().registerReceiver(areaChangeBroadcastReceiver,
                new IntentFilter(HeaderView.action));

        distance = null;
        addDate = false;
        repairShopPager.reset();
        getData();
        initMap();
    }

    /*
     * private IXListViewListener onRepairShopViewListener = new
     * IXListViewListener() {
     * 
     * @Override public void onRefresh() { addDate = false;
     * repairShopPager.reset(); repairShopList.getmFooterView().setState(
     * XListViewFooter.STATE_NORMAL); getData(); }
     * 
     * @Override public void onLoadMore() { LogUtils.e("the data is loading");
     * addDate = true; getData(); } };
     */

    /**
     * 停止刷新，
     */
    /*
     * private void onStopLoad() { repairShopList.stopRefresh();
     * repairShopList.stopLoadMore(); repairShopList.setRefreshTime("刚刚"); }
     */

    /**
     * 
     * @param distance
     *            周边范围距离，单位公里
     */
    public void getData() {
        /*String key = SearchActivity.searchKey;
        if (RegexUtil.isNotNull(key)) {
            distance = null;
            orderView.setEnabled(false);
            orderView.setVisibility(View.GONE);
            repairShopPager.getSearchData(key, callbackList);
        } else */if (distance != null) {
            orderView.setEnabled(true);
            orderView.setVisibility(View.VISIBLE);

            new Handler().postDelayed(new Runnable() {
                public void run() {
                    if (!getCar91Application().isLocating()) {
                        new Builder(getActivity())
                                .setMessage("网络环境较差，定位可能需花点时间").create().show();
                    }
                }
            }, 8 * 1000);

            LocationClient locationClient = getCar91Application()
                    .getmLocationClient();

            if (getCar91Application().isLocating()) {
                BDLocation location = getCar91Application()
                        .getmLocationClient().getLastKnownLocation();
                Location myLocation = EarthUtil.getLocationRadius(
                        location.getLatitude(), location.getLongitude(),
                        distance);// distance km范围内
                repairShopPager.getAroundData(location.getLatitude(),
                        location.getLongitude(), myLocation.lat,
                        myLocation.lon, orderby, rgrade, callbackList);
            } else {
                locationClient.requestOfflineLocation();
                new Builder(getActivity()).setMessage("正在定位中...").create()
                        .show();
            }
        } else {
            orderView.setEnabled(true);
            orderView.setVisibility(View.VISIBLE);
            repairShopPager.getPublicData(orderby, rgrade, areaParam, callbackList);
        }
    }

    /* 列表页面 */
    private void refreshListViewData(List data) {
        if (addDate) {
            // if(scrollView.getVisibility()==View.VISIBLE){
            repairShopListAdapter.addData(data);
            // }
        } else {
            // if(scrollView.getVisibility()==View.VISIBLE){
            repairShopList.removeAllViewsInLayout();
            repairShopListAdapter.setData(data);
            // }
        }
        repairShopListAdapter.notifyDataSetChanged();
        addDate = true;
    }

    /**
     * 回调获取商家列表
     */
    private RequestCallBack callbackList = new RequestCallBack() {

        @Override
        public void onStart() {
            // TODO Auto-generated method stub
            super.onStart();
            showTextWhenNone(false);
        }

        @Override
        public void onFailure(HttpException arg0, String arg1) {
            Toast.makeText(getActivity(), "网络异常~", Toast.LENGTH_SHORT).show();
            // onStopLoad();
            pullToRefreshView.onFooterRefreshComplete();
            pullToRefreshView.onHeaderRefreshComplete();
            showTextWhenNone(false);
        }

        @Override
        public void onSuccess(ResponseInfo arg0) {
            List<RepairShop> repairShops = Car91JsonUtil.getDTOList(
                    arg0.result.toString(), RepairShop.class);
            // onStopLoad();
            if (repairShops.size() > 0) {
                showTextWhenNone(false);
            } else if (!addDate) {
                showTextWhenNone(true);
            } else {
                /*
                 * repairShopList .getmFooterView() .getmHintView() .setText(
                 * getResources().getString(
                 * R.string.xlistview_footer_hint_nomore));
                 */
            }
            pullToRefreshView.setLastUpdated(new Date().toLocaleString());
            pullToRefreshView.onFooterRefreshComplete();
            pullToRefreshView.onHeaderRefreshComplete();
            refreshListViewData(repairShops);
        }

        private void showTextWhenNone(Boolean show) {
            View container = repairShopList;
            if (show) {
                if (container.getVisibility() == View.VISIBLE) {
                    container.setVisibility(View.GONE);
                }
                if (none.getVisibility() == View.GONE) {
                    none.setVisibility(View.VISIBLE);
                }
            } else {
                if (container.getVisibility() == View.GONE) {
                    container.setVisibility(View.VISIBLE);
                }
                if (none.getVisibility() == View.VISIBLE) {
                    none.setVisibility(View.GONE);
                }
            }
        }
    };

    @Override
    public void onListItemClick(ListView l, View v, int position, long id) {
        super.onListItemClick(l, v, position, id);

        String rid = repairShopListAdapter.getRepairShopId(position);// xUtils
        // arg2起始为1

        Intent intent = new Intent();
        intent.putExtra("rid", rid);
        intent.setClass(getActivity(), RepairShopDetailActivity.class);
        startActivity(intent);
    }

    /*
     * @OnItemClick(R.id.repairshop_list) public void
     * onListItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
     * String rid = repairShopListAdapter.getRepairShopId(arg2 - 1);// xUtils //
     * arg2起始为1
     * 
     * Intent intent = new Intent(); intent.putExtra("rid", rid);
     * intent.setClass(getActivity(), RepairShopDetailActivity.class);
     * startActivity(intent); }
     */

    interface OrderBy {
        /**
         * 默认综合降序
         */
        final String Default = "00";
        /**
         * 默认综合升序
         */
        final String OpDefault = "01";
        /**
         * 好评度降序
         */
        final String Good = "10";
        /**
         * 好评度升序
         */
        final String OpGood = "11";
        /**
         * 入驻时间降序
         */
        final String Reg = "20";
        /**
         * 入驻时间升序
         */
        final String OpReg = "21";
        /**
         * 评论量降序
         */
        final String Comment = "30";
        /**
         * 评论量升序
         */
        final String OpComment = "31";
    }

    // 排序
    @SuppressLint("NewApi") private void initSort() {
		initPopupWindow();
		getDistrict(getCar91Application().getPlacePreferences().getInt("city",
				-1));

		orderView.getChildAt(0).setOnClickListener(onAreaClickListener);
		for (int index = 2; index < orderView.getChildCount(); index++) {
			View view = orderView.getChildAt(index);
			view.setOnClickListener(onSortClickListener);
		}
		
		rgradeSpinner.setDropDownWidth(DensityUtils.dp2px(getActivity(), MobileUtils.getScreenWidth(getActivity())));
		rgradeSpinner.setAdapter(new ArrayAdapter<String>(getActivity(), R.layout.view_spinner_select, getResources().getStringArray(R.array.repairshop_rgrades)));
		rgradeSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> arg0, View arg1,
                    int arg2, long arg3) {
                rgrade = (int) (arg3-1);
                if(0>rgrade) {
                    rgrade = null;
                }
                addDate = false;
                repairShopPager.reset();
                getData();
            }

            @Override
            public void onNothingSelected(AdapterView<?> arg0) {
                // TODO Auto-generated method stub
                
            }
        });
	}

    private OnClickListener onAreaClickListener = new OnClickListener() {
        @Override
        public void onClick(View arg0) {
            turnPopuWindow();
        }
    };

    private void turnPopuWindow() {
        try {
            if (popupWindow != null) {
                if (popupWindow.isShowing()) {
                    closePopupWindow();
                } else {
                    openPopupWindow();
                }
            }
        } catch (Exception e) {
        }
    }

    private OnClickListener onSortClickListener = new OnClickListener() {

        private void changeView() {
            Drawable drawable = null;
            for (int index = 0; index < orderView.getChildCount(); index++) {
                try {
                    TextView view = (TextView) ((LinearLayout) orderView
                            .getChildAt(index)).getChildAt(0);
                    view.setTextColor(getResources().getColor(
                            android.R.color.black));
                    drawable = getResources().getDrawable(R.drawable.sort_down);
                    drawable.setBounds(0, 0, drawable.getMinimumWidth(),
                            drawable.getMinimumHeight());
                    view.setCompoundDrawables(null, null, drawable, null);
                } catch (Exception e) { }
            }
            TextView textView = null;
            if (orderby.startsWith("0")) {
                textView = (TextView) ((LinearLayout) orderView.getChildAt(0))
                        .getChildAt(0);
                textView.setTextColor(getResources().getColor(
                        R.color.theme_color));
                if (orderby.endsWith("0")) {
                    drawable = getResources().getDrawable(
                            R.drawable.sort_down_cur);
                } else {
                    drawable = getResources().getDrawable(
                            R.drawable.sort_up_cur);
                }
            } else if (orderby.startsWith("1")) {
                textView = (TextView) ((LinearLayout) orderView.getChildAt(2))
                        .getChildAt(0);
                textView.setTextColor(getResources().getColor(
                        R.color.theme_color));
                if (orderby.endsWith("0")) {
                    drawable = getResources().getDrawable(
                            R.drawable.sort_down_cur);
                } else {
                    drawable = getResources().getDrawable(
                            R.drawable.sort_up_cur);
                }
            }
            // else if (orderby.startsWith("3")) {
            // textView = (TextView) ((LinearLayout) orderView.getChildAt(3))
            // .getChildAt(0);
            // textView.setTextColor(getResources().getColor(
            // R.color.theme_color));
            // if (orderby.endsWith("0")) {
            // drawable = getResources().getDrawable(
            // R.drawable.sort_down_cur);
            // } else {
            // drawable = getResources().getDrawable(
            // R.drawable.sort_up_cur);
            // }
            // }
            if (textView != null) {
                drawable.setBounds(0, 0, drawable.getMinimumWidth(),
                        drawable.getMinimumHeight());
                textView.setCompoundDrawables(null, null, drawable, null);
            }
        }

        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub
            closePopupWindow();

            int viewId = arg0.getId();
            switch (viewId) {
            case R.id.repairshop_list_area:
                break;
            case R.id.repairshop_list_order_sgrade:
                break;
            case R.id.repairshop_list_order_comment:
                if (orderby.startsWith("1")) {
                    if (orderby.endsWith("0")) {
                        orderby = OrderBy.OpGood;
                    } else {
                        orderby = OrderBy.Good;
                    }
                } else {
                    orderby = OrderBy.Good;
                }
                break;
            default:
                break;
            }
            addDate = false;
            repairShopPager.reset();
            getData();
            changeView();
        }
    };

    // 区域栏
    private void getDistrict(int cid) {
        TextView t = (TextView) ((LinearLayout) orderView.getChildAt(0))
                .getChildAt(0);
        radioGroupFirst.removeAllViews();
        radioGroupSecond.removeAllViews();
        RadioButton deButton = _createRadioBtn(0, "附近",
                R.drawable.selector_area_bg_color);
        cityName = "附近";
        deButton.setChecked(true);
        radioGroupFirst.addView(deButton);
        if (cid > 0) {
            t.setText("全市");
            HttpHandler.httpHandler.getCityDistricts(cid, callBackDistrict);
        } else {
            t.setText("附近");
            districts = new ArrayList<District>();
        }
        if (RegexUtil.isNull(areaParam.paramName)
                || areaParam.paramName.equals("cid")) {
            //radioGroupFirst.check(0);
            _getAround();
        }
        radioGroupFirst
        .setOnCheckedChangeListener(onDistrictCheckedChangeListener);
    }

    private void getStreet(int did) {
        radioGroupSecond.removeAllViews();
        radioGroupSecond.addView(_createRadioBtn(0, "全区",
                R.drawable.layer_area_default_white));
        if (did > 0) {
            HttpHandler.httpHandler.getDistrictStreets(did, callBackStreet);
        } else {
            streets = new ArrayList<Street>();
        }
    }

    private String cityName="";
    private OnCheckedChangeListener onDistrictCheckedChangeListener = new OnCheckedChangeListener() {

        @Override
        public void onCheckedChanged(RadioGroup arg0, int arg1) {
            // TODO Auto-generated method stub
            View btn = arg0.findViewById(arg1);

            /*TextView t = (TextView) ((LinearLayout) orderView.getChildAt(0))
                    .getChildAt(0);*/
            if (btn != null) {
                cityName = ((RadioButton) btn).getText().toString();
            }
            
            if (arg1 > 0) {
                try {
                    getStreet(districts.get(arg1 - 1).getDid());
                } catch (Exception e) { }
            } else {
                /*
                 * addDate = false; repairShopPager.reset(); areaParam.paramName
                 * = "cid"; areaParam.paramValue =
                 * String.valueOf(getCar91Application()
                 * .getPlacePreferences().getInt("city", -1)); getData();
                 * turnPopuWindow();
                 */
                _getAround();
            }
        }
    };

    private void _getAround() {
        radioGroupSecond.removeAllViews();
        RadioButton defaultButton = _createRadioBtn(-2000, "默认",
                R.drawable.layer_area_default_white);
        //defaultButton.setChecked(true);
        radioGroupSecond.addView(defaultButton);
        radioGroupSecond.addView(_createRadioBtn(-5, "500米",
                R.drawable.layer_area_default_white));
        radioGroupSecond.addView(_createRadioBtn(-10, "1000米",
                R.drawable.layer_area_default_white));
        radioGroupSecond.addView(_createRadioBtn(-20, "2000米",
                R.drawable.layer_area_default_white));
        radioGroupSecond.addView(_createRadioBtn(-50, "5000米",
                R.drawable.layer_area_default_white));
        radioGroupSecond
        .setOnCheckedChangeListener(new OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup arg0,
                    int arg1) {
                TextView t = (TextView) ((LinearLayout) orderView.getChildAt(0))
                        .getChildAt(0);
                String tmp = "附近";
                switch (arg1) {
                case -5:
                    tmp = "500米";
                    break;
                case -10:
                    tmp = "1公里";
                    break;
                case -20:
                    tmp = "2公里";
                    break;
                case -50:
                    tmp = "5公里";
                    break;
                default:
                    tmp = "附近";
                    break;
                }
                t.setText(tmp);
                addDate = false;
                repairShopPager.reset();
                distance = -arg1 / 10f;
                getData();
                closePopupWindow();
            }
        });
    }

    private RadioButton _createRadioBtn(int id, String name,
            int defaultBackground) {
        RadioButton defaultButton = new RadioButton(getActivity());
        defaultButton.setId(id);
        defaultButton.setText(name);
        defaultButton.setTextSize(18);
        defaultButton.setBackgroundResource(defaultBackground);
        defaultButton.setTextColor(getResources().getColorStateList(
                R.color.selector_area_font_color));
        defaultButton.setPadding(30, 18, 12, 18);
        defaultButton.setLayoutParams(new LayoutParams(
                LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
        defaultButton.setButtonDrawable(new ColorDrawable(Color.TRANSPARENT));
        return defaultButton;
    }

    private RequestCallBack callBackDistrict = new RequestCallBack() {

        @Override
        public void onFailure(HttpException arg0, String arg1) {
            LogUtils.e("internet is error and " + arg1);
        }

        @Override
        public void onSuccess(ResponseInfo arg0) {
            districts = new ArrayList<District>();
            districts = Car91JsonUtil.getDTOList(arg0.result.toString(),
                    District.class);

            if (districts != null) {
                for (District d : districts) {
                    radioGroupFirst.addView(_createRadioBtn(d.getDid(),
                            d.getName(), R.drawable.selector_area_bg_color));
                }
            }
        }
    };

    private OnCheckedChangeListener onStreetCheckedChangeListener = new OnCheckedChangeListener() {

        @Override
        public void onCheckedChanged(RadioGroup arg0, int arg1) {
            // TODO Auto-generated method stub
            View btn = arg0.findViewById(arg1);
            TextView t = (TextView) ((LinearLayout) orderView.getChildAt(0))
                    .getChildAt(0);
            if (btn != null) {
                String tmp = ((RadioButton) btn).getText().toString();
                if (!tmp.equals("全区")&&!tmp.equals("默认")) {
                    t.setText(tmp);
                } else {
                    t.setText(cityName);
                }

                addDate = false;
                distance = null;
                repairShopPager.reset();

                if (arg1 == 0) {
                    areaParam.paramName = "did";
                    areaParam.paramValue = String.valueOf(radioGroupFirst
                            .getCheckedRadioButtonId());
                } else {
                    areaParam.paramName = "sid";
                    areaParam.paramValue = String.valueOf(arg1);
                }
                getData();
                turnPopuWindow();
            }
        }
    };

    private RequestCallBack callBackStreet = new RequestCallBack() {

        @Override
        public void onFailure(HttpException arg0, String arg1) {
            LogUtils.e("internet is error and " + arg1);
        }

        @Override
        public void onSuccess(ResponseInfo arg0) {
            // TODO Auto-generated method stub
            streets = new ArrayList<Street>();
            streets = Car91JsonUtil.getDTOList(arg0.result.toString(),
                    Street.class);
            if (streets != null) {
                for (Street s : streets) {
                    radioGroupSecond.addView(_createRadioBtn(s.getSid(),
                            s.getName(), R.drawable.layer_area_default_white));
                }
            }

            radioGroupSecond
                    .setOnCheckedChangeListener(onStreetCheckedChangeListener);
        }
    };

    // 区域栏 End

    private void openPopupWindow() {
        if (radioGroupFirst.getChildCount() <= 0) {
            new HerilyAlertDialog.Builder(getActivity()).setMessage("请先选择城市")
                    .create().show();
            return;
        }

        if (popupWindow != null)
            if (!popupWindow.isShowing()) {
                placeList.getChildAt(0).setLayoutParams(
                        new LinearLayout.LayoutParams(
                                LinearLayout.LayoutParams.MATCH_PARENT,
                                ((View) repairShopList.getParent())
                                        .getMeasuredHeight()));
                placeList.setPadding(
                        0,
                        (int) (getResources().getDimension(
                                R.dimen.header_height) + orderView
                                .getMeasuredHeight()), 0, 0);
                popupWindow.setContentView(placeList);
                popupWindow.showAtLocation(orderView.getRootView(),
                        Gravity.TOP, 0, 0);
                
                if(distance!=null){
                    _getAround();
                }
            }
    }

    private void closePopupWindow() {
        try {
            if (popupWindow != null)
                if (popupWindow.isShowing())
                    popupWindow.dismiss();
        } catch (Exception e) { }
    }

    private void initPopupWindow() {
        popupWindow = new PopupWindow(placeList, LayoutParams.MATCH_PARENT,
                LayoutParams.MATCH_PARENT);
        popupWindow.setTouchable(true);
        popupWindow.setAnimationStyle(R.style.area_popu_anim_style);
    }

    private void initMap() {
        View view = getActivity().findViewById(R.id.imgBtn_map);
        view.setOnClickListener(new OnClickListener() {
            
            @Override
            public void onClick(View arg0) {
                if(repairShopListAdapter.getCount()>0) {
                    LocationClient locationClient = getCar91Application().getmLocationClient();
                    if (getCar91Application().isLocating()) {
                        BDLocation location = locationClient.getLastKnownLocation();
                        Intent intent = new Intent(getActivity(), MapActivity.class);
                        intent.putExtra("mapType", MapType.MAP_TYPE_AOUND_REPAIRSHOP);
                        intent.putExtra("lon", location.getLongitude());
                        intent.putExtra("lat", location.getLatitude());
                        intent.putExtra("zoom", 16);
                        intent.putExtra("points", (Serializable) repairShopListAdapter.getData());
                        getActivity().startActivity(intent);
                    } else {
                        locationClient.requestOfflineLocation();
                        new Builder(getActivity()).setMessage("正在定位中，请稍后再试...").create().show();
                    }
                } else {
                    new Builder(getActivity()).setMessage("对不起，该区域暂无商家数据").create().show();
                }
            }
        });
    }
    
    @Override
    public void onDestroy() {
        getActivity().unregisterReceiver(areaChangeBroadcastReceiver);
        super.onDestroy();
    }

    private BroadcastReceiver areaChangeBroadcastReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context arg0, Intent arg1) {
            closePopupWindow();

            int cid = getCar91Application().getPlacePreferences().getInt(
                    "city", -1);
            getDistrict(cid);

            distance = null;
            addDate = false;
            repairShopPager.reset();
            areaParam.paramName = "cid";
            areaParam.paramValue = String.valueOf(cid);
            getData();
        }
    };
}
